<template>
  <div class="flex justify-between">
    <n-space border-b="1px solid #ddd" dark:border-b="1px solid #404040">
      <n-tag :checked="checkedLang.all" checkable @update:checked="updateCheckedAll">不限</n-tag>
      <n-tag
        :checked="checkedLang.C"
        checkable
        @update:checked="(checked) => updateCheckedOneHandler('C')(checked)"
      >
        C
      </n-tag>
      <n-tag
        :checked="checkedLang['C++']"
        checkable
        @update:checked="(checked) => updateCheckedOneHandler('C++')(checked)"
      >
        C++
      </n-tag>
      <n-tag
        :checked="checkedLang.Java"
        checkable
        @update:checked="(checked) => updateCheckedOneHandler('Java')(checked)"
      >
        Java
      </n-tag>
      <n-tag
        :checked="checkedLang.Python"
        checkable
        @update:checked="(checked) => updateCheckedOneHandler('Python')(checked)"
      >
        Python
      </n-tag>
    </n-space>
    <slot name="func"></slot>
  </div>
  <div class="py-16">
    <slot :comments="comments"></slot>
  </div>
</template>

<script setup>
import api from '@/api/user'

const props = defineProps({
  problemId: {
    type: String,
    required: true,
  },
  immediate: {
    type: Boolean,
    default: true,
  },
  reviewStatus: {
    type: String,
    default: 'pass',
  },
})

const checkedLang = reactive({
  all: true,
  C: false,
  'C++': false,
  Java: false,
  Python: false,
})
const comments = ref([])

const updateCheckedAll = (checked) => {
  if (checked) {
    checkedLang.all = checked
    checkedLang['C'] = false
    checkedLang['C++'] = false
    checkedLang['Java'] = false
    checkedLang['Python'] = false
  }
}

const updateCheckedOneHandler = (key) => (checked) => {
  checkedLang[key] = checked
  if (checked) {
    if (checkedLang.all === true) checkedLang.all = false
  } else if (
    !checkedLang['C'] &&
    !checkedLang['C++'] &&
    !checkedLang['Java'] &&
    !checkedLang['Python']
  ) {
    checkedLang.all = true
  }
}

const getProblemComments = async (reviewStatus = 'pass') => {
  const languages = Object.keys(checkedLang).filter((key) => {
    return checkedLang[key]
  })

  try {
    const res = await api.getProblemCommentsByProId({
      problemId: props.problemId,
      reviewStatus,
      languages: languages.includes('all') ? undefined : languages,
    })
    if (res.data) {
      comments.value = res.data
    }
  } catch (err) {
    console.log(err)
  }
}

defineExpose({
  getProblemComments,
})

// 题解类型变化时
watch(checkedLang, () => {
  getProblemComments(props.reviewStatus)
})

onMounted(() => {
  if (props.immediate) {
    getProblemComments(props.reviewStatus)
  }
})
</script>
